import 'package:bitcoin_mine/services/in_app_purchase_service.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:in_app_purchase/in_app_purchase.dart';
import '../controllers/home_controller.dart';
import '../common/global.dart';
import '../model/mine_info.dart';

class SubscriptionPlans extends StatelessWidget {
  const SubscriptionPlans({super.key});

  @override
  Widget build(BuildContext context) {
    final HomeController controller = Get.find();
    final InAppPurchaseService inAppPurchaseService =
        Get.find<InAppPurchaseService>();

    return Container(
      margin: EdgeInsets.symmetric(horizontal: 15.w),
      child: Obx(() {
        final MineInfo? mineInfo = Global.mineInfo.value;
        final int tier = controller.selectedTier.value;
        final List<Good> goods = _goodsByTier(mineInfo, tier);

        return Stack(
          children: [
            // if (inAppPurchaseService.isPurchasing.value)
            Column(
              children:
                  goods.asMap().entries.map((entry) {
                    final index = entry.key;
                    final good = Global.goods.firstWhere(
                      (element) => element.product_id == entry.value.product_id,
                    );
                    final ProductDetails? productInfo = inAppPurchaseService
                        .getProductInfo(good.product_id);
                    final String periodText = _periodText(good.circle);
                    final String priceText =
                        '${good.discount_price != null ? '${productInfo?.currencySymbol}${good.discount_price}' : '${productInfo?.price}'}/';
                    final String speedText =
                        '${good.hashrate.toStringAsFixed(2)} Gh/s';
                    final String detailsText =
                        '+ Continuous improvement\nMining speed';
                    final String? promo =
                        good.promotional.isNotEmpty
                            ? "${good.promotional}%"
                            : null;
                    // final double nextPrice = ;

                    // '${good.discount_price != null ? '${productInfo?.currencySymbol}${good.discount_price}' : '${productInfo?.price}'}/';
                    final String nextText =
                        'The next: ${productInfo?.price}/$periodText';

                    return Container(
                      margin: const EdgeInsets.only(bottom: 8),
                      child: Card(
                        child: InkWell(
                          onTap: () {
                            controller.selectPlan(index);
                            inAppPurchaseService.purchaseProduct(
                              controller.getCurrentProduct(),
                            );
                          },
                          child: Container(
                            padding: EdgeInsets.only(
                              left: 15.r,
                              right: 10.r,
                              bottom: 10.r,
                            ),
                            decoration: BoxDecoration(
                              image: const DecorationImage(
                                image: AssetImage(
                                  'assets/images/bg_selection.png',
                                ),
                                fit: BoxFit.fill,
                              ),
                            ),
                            child: Row(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    SizedBox(height: 15.h),
                                    Row(
                                      crossAxisAlignment:
                                          CrossAxisAlignment.baseline,
                                      textBaseline: TextBaseline.alphabetic,
                                      children: [
                                        Text(
                                          priceText,
                                          style: Theme.of(
                                            context,
                                          ).textTheme.headlineSmall?.copyWith(
                                            color: const Color(0xFF05FFFD),
                                            fontWeight: FontWeight.w600,
                                            fontSize: 22.sp,
                                          ),
                                        ),
                                        Text(
                                          periodText,
                                          style: Theme.of(
                                            context,
                                          ).textTheme.bodySmall?.copyWith(
                                            color: Color(0xFF05FFFD),
                                            fontSize: 16.sp,
                                            fontWeight: FontWeight.w600,
                                          ),
                                        ),
                                      ],
                                    ),
                                    SizedBox(height: 3.h),
                                    Text(
                                      nextText,
                                      style: Theme.of(
                                        context,
                                      ).textTheme.bodySmall?.copyWith(
                                        color: Colors.white,
                                        fontSize: 11.sp,
                                        fontWeight: FontWeight.w400,
                                      ),
                                    ),
                                  ],
                                ),
                                SizedBox(width: 3.w),
                                Expanded(
                                  child: Column(
                                    crossAxisAlignment:
                                        CrossAxisAlignment.center,
                                    children: [
                                      SizedBox(height: 15.h),
                                      Text(
                                        speedText,
                                        textAlign: TextAlign.center,
                                        style: Theme.of(
                                          context,
                                        ).textTheme.bodySmall?.copyWith(
                                          color: const Color(0xFF05FFFD),
                                          fontSize: 16.sp,
                                          fontWeight: FontWeight.w600,
                                        ),
                                      ),
                                      SizedBox(height: 2.h),
                                      Text(
                                        detailsText,
                                        textAlign: TextAlign.center,
                                        style: Theme.of(
                                          context,
                                        ).textTheme.bodySmall?.copyWith(
                                          color: const Color(0xFF05FFFD),
                                          fontWeight: FontWeight.w400,
                                          fontSize: 9.sp,
                                        ),
                                      ),
                                    ],
                                  ),
                                ),
                                Column(
                                  children: [
                                    if (promo != null)
                                      Container(
                                        padding: EdgeInsets.symmetric(
                                          horizontal: 6.w,
                                          vertical: 4.h,
                                        ),
                                        decoration: BoxDecoration(
                                          color: const Color(0xFF05FFFD),
                                          borderRadius: BorderRadius.circular(
                                            60.r,
                                          ),
                                        ),
                                        child: Text(
                                          promo,
                                          style: TextStyle(
                                            color: const Color(0xFF0A0E27),
                                            fontSize: 12.sp,
                                            fontWeight: FontWeight.w600,
                                          ),
                                        ),
                                      ),
                                    Obx(() {
                                      final bool isSelected =
                                          index ==
                                          controller.selectedPlan.value;
                                      return Container(
                                        width: 24.r,
                                        height: 24.r,
                                        decoration: BoxDecoration(
                                          color:
                                              isSelected
                                                  ? const Color(0xFF004BB3)
                                                  : Color(0xff486A8F),
                                          border: Border.all(
                                            color: const Color(0xFF05FFFD),
                                            width: 2,
                                          ),
                                          borderRadius: BorderRadius.circular(
                                            4,
                                          ),
                                        ),
                                        child:
                                            isSelected
                                                ? Icon(
                                                  Icons.check,
                                                  color: Color(0xFFFFFFFF),
                                                  size: 16.sp,
                                                )
                                                : null,
                                      );
                                    }),
                                  ],
                                ),
                              ],
                            ),
                          ),
                        ),
                      ),
                    );
                  }).toList(),
            ),
            Obx(() {
              if (inAppPurchaseService.isPurchasing.value) {
                return Container(
                  color: Colors.black.withValues(alpha: 0.5),
                  width: double.infinity,
                  height: 250.h,
                  child: Center(child: CircularProgressIndicator()),
                );
              }
              return Container();
            }),
          ],
        );
      }),
    );
  }
}

List<Good> _goodsByTier(MineInfo? info, int tier) {
  if (info == null) return [];
  switch (tier) {
    case 0:
      return info.goods_map.group1;
    case 1:
      return info.goods_map.group2;
    case 2:
      return info.goods_map.group3;
    case 3:
      return info.goods_map.group4;
    default:
      return info.goods_map.group1;
  }
}

String _periodText(int circle) {
  switch (circle) {
    case 1:
      return 'week';
    case 2:
      return 'month';
    case 3:
      return 'season';
    case 4:
      return 'year';
    default:
      return 'month';
  }
}

double _calcNextPrice(double price, String? promotional) {
  if (promotional == null || promotional.isEmpty) {
    return price * 1.2;
  }
  final percent = int.tryParse(promotional.replaceAll(RegExp(r'[^0-9]'), ''));
  if (percent == null || percent <= 0 || percent >= 100) {
    return price * 1.2;
  }
  final p = percent / 100.0;
  return price / (1 - p);
}
